package com.zdx.yswl.view.listview.drag;



import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

public class DragListViewController implements OnTouchListener, OnScrollListener {

	protected ListView mListView;

	private DrapFootStateEnum mFootState = DrapFootStateEnum.FOOT_NORMAL_STATE;// 加载更多默认状态.
	private DrapHeadStateEnum mHeadState = DrapHeadStateEnum.HEAD_NORMAL_STATE;// 拖拉状态.(自定义枚举)

	public DrapRefreshDelegate refreshDelegate;// 下拉刷新接口（自定义）
	private DrapHeadDelegate mHeadDelegate;// 头部headView
	private DrapFootDelegate mFootDelegate;// 尾部mFootView

	private int mHeadViewHeight;// headView的高（mHeadView）
	private int mFirstItemIndex = -1;// 当前视图能看到的第一个项的索引
	private boolean mIsRecord = false;// 用于保证startY的值在一个完整的touch事件中只被记录一次
	private int mStartY, mMoveY;// 按下是的y坐标,move时的y坐标
	private final static int RATIO = 2;// 手势下拉距离比.
	// private boolean mBack = false;// headView是否返回.
	private boolean isScroller = true;// 是否屏蔽ListView滑动。

	public DragListViewController(ListView _listView) {
		super();
		this.mListView = _listView;
		this.mListView.setOnScrollListener(this);// ListView滚动监听
		this.mListView.setOnTouchListener(this);
	}

	/*设置头部View*/
	public void setHeadDelegate(DrapHeadDelegate _headDelegate) {
		if (_headDelegate == null || this.mHeadDelegate == _headDelegate) {
			return;
		}
		this.mHeadDelegate = _headDelegate;
		this.mHeadState = DrapHeadStateEnum.HEAD_NORMAL_STATE;
		this._measureView(mHeadDelegate.getView());
		this.mHeadViewHeight = mHeadDelegate.getView().getMeasuredHeight();
		this.mListView.addHeaderView(mHeadDelegate.getView(), null, false);
		this.mHeadDelegate.getView().setPadding(0, -1 * mHeadViewHeight, 0, 0);
	}

	public DrapHeadDelegate getHeadDelegate() {
		return this.mHeadDelegate;
	}

	/*设置底部View*/
	public void setFootDelegate(DrapFootDelegate _footDelegate) {
		if (_footDelegate == null || this.mFootDelegate == _footDelegate) {
			return;
		}
		this.mFootDelegate = _footDelegate;
		this.mFootState = DrapFootStateEnum.FOOT_NORMAL_STATE;
		this.mListView.addFooterView(mFootDelegate.getView());
	}

	public DrapFootDelegate getFootDelegate() {
		return this.mFootDelegate;
	}

	/***
	 * 下拉刷新
	 */
	public void doHeadRefresh() {
		if (mHeadDelegate != null && mHeadState == DrapHeadStateEnum.HEAD_NORMAL_STATE) {
			mHeadDelegate.getView().setPadding(0, 0, 0, 0);
			_switchHeadState(DrapHeadStateEnum.HEAD_LOADING_STATE);
			refreshDelegate.onHeadRefresh();
		}

	}

	public void showHeadRefresh() {
		if (mHeadDelegate != null && mHeadState == DrapHeadStateEnum.HEAD_NORMAL_STATE) {
			mHeadDelegate.getView().setPadding(0, 0, 0, 0);
			_switchHeadState(DrapHeadStateEnum.HEAD_LOADING_STATE);
		}
	}

	/***
	 * 下拉刷新完毕
	 */
	public void headRefreshCompleted() {
		if (mHeadDelegate != null) {
			mHeadDelegate.getView().setPadding(0, -1 * mHeadViewHeight, 0, 0);// 回归.
			_switchHeadState(DrapHeadStateEnum.HEAD_NORMAL_STATE);
		}
	}

	public void doFootRefresh() {
		if (refreshDelegate != null && mFootState == DrapFootStateEnum.FOOT_NORMAL_STATE) {
			_switchFootState(DrapFootStateEnum.FOOT_LOADING_STATE);
			mFootState = DrapFootStateEnum.FOOT_LOADING_STATE;
			refreshDelegate.onFootRefresh();// 对外提供方法加载更多.
		}
	}

	public void footRefreshCompleted(boolean flag) {
		if (flag) {
			_switchFootState(DrapFootStateEnum.FOOT_OVER_STATE);
		} else {
			_switchFootState(DrapFootStateEnum.FOOT_NORMAL_STATE);
		}
	}

	private void _measureView(View child) {
		ViewGroup.LayoutParams p = child.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		}
		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}

	private void _switchHeadState(DrapHeadStateEnum state) {
		if (mHeadDelegate == null) {
			return;
		}
		if (state == DrapHeadStateEnum.HEAD_NORMAL_STATE) {
			mHeadDelegate.setNormalState();
		} else if (state == DrapHeadStateEnum.HEAD_PULL_REFRESH_STATE) {
			mHeadDelegate.setPullRefreshState();

			// 是有可刷新状态（LV_RELEASE_REFRESH）转为这个状态才执行，其实就是你下拉后在上拉会执行.
			// if (mBack) {
			// mBack = false;
			// mArrowImageView.clearAnimation();// 清除动画
			// mArrowImageView.startAnimation(reverseAnimation);// 启动反转动画
			// }
		} else if (state == DrapHeadStateEnum.HEAD_RELEASE_REFRESH_STATE) {
			mHeadDelegate.setReleaseRefreshState();
		} else if (state == DrapHeadStateEnum.HEAD_LOADING_STATE) {
			mHeadDelegate.setLoadingState();
		} else {
			return;
		}
		mHeadState = state;
	}

	private void _switchFootState(DrapFootStateEnum state) {
		if (this.mFootDelegate == null) {
			return;
		}
		if (state == DrapFootStateEnum.FOOT_NORMAL_STATE) {
			this.mFootDelegate.setNormalState();
		} else if (state == DrapFootStateEnum.FOOT_LOADING_STATE) {
			this.mFootDelegate.setLoadingState();
		} else if (state == DrapFootStateEnum.FOOT_OVER_STATE) {
			this.mFootDelegate.setLoadedState();
		} else {
			return;
		}
		mFootState = state;
	}

	// ----------------------- OnTouchListener -----------------------
	@Override
	public boolean onTouch(View v, MotionEvent ev) {
		if (v != this.mListView) {
			return false;
		}
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			_doActionDown(ev);
		} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
			_doActionMove(ev);
		} else if (ev.getAction() == MotionEvent.ACTION_UP) {
			_doActionUp(ev);
		}

		/***
		 * 如果是ListView本身的拉动，那么返回true，这样ListView不可以拖动.
		 * 如果不是ListView的拉动，那么调用父类方法，这样就可以上拉执行.
		 */
		if (isScroller) {
			return false;
		} else {
			return true;
		}

	}

	private void _doActionDown(MotionEvent event) {
		if (mIsRecord == false && mFirstItemIndex == 0) {
			mStartY = (int) event.getY();
			mIsRecord = true;
		}
	}

	private void _doActionMove(MotionEvent event) {
		if (mHeadDelegate == null) {
			return;
		}
		mMoveY = (int) event.getY();// 获取实时滑动y坐标
		// 检测是否是一次touch事件.
		if (mIsRecord == false && mFirstItemIndex == 0) {
			mStartY = (int) event.getY();
			mIsRecord = true;
		}
		/***
		 * 如果touch关闭或者正处于Loading状态的话 return.
		 */
		if (mIsRecord == false || mHeadState == DrapHeadStateEnum.HEAD_LOADING_STATE) {
			return;
		}
		// 向下啦headview移动距离为y移动的一半.（比较友好）
		int offset = (mMoveY - mStartY) / RATIO;

		if (mHeadState == DrapHeadStateEnum.HEAD_NORMAL_STATE) {
			if (offset > 0) {
				mHeadDelegate.getView().setPadding(0, offset - mHeadViewHeight, 0, 0);
				_switchHeadState(DrapHeadStateEnum.HEAD_PULL_REFRESH_STATE);// 下拉状态
			}
		} else if (mHeadState == DrapHeadStateEnum.HEAD_PULL_REFRESH_STATE) {
			this.mListView.setSelection(0);// 选中第一项，可选.
			// 设置headView的padding属性.
			mHeadDelegate.getView().setPadding(0, offset - mHeadViewHeight, 0, 0);
			if (offset < 0) {
				isScroller = false;
				_switchHeadState(DrapHeadStateEnum.HEAD_NORMAL_STATE);// 普通状态
			} else if (offset > mHeadViewHeight) {// 如果下拉的offset超过headView的高度则要执行刷新.
				_switchHeadState(DrapHeadStateEnum.HEAD_RELEASE_REFRESH_STATE);// 更新为可刷新的下拉状态.
			}
		} else if (mHeadState == DrapHeadStateEnum.HEAD_RELEASE_REFRESH_STATE) {
			this.mListView.setSelection(0);
			mHeadDelegate.getView().setPadding(0, offset - mHeadViewHeight, 0, 0);
			// 下拉offset>0，但是没有超过headView的高度.那么要goback 原装.
			if (offset >= 0 && offset <= mHeadViewHeight) {
				// mBack = true;
				_switchHeadState(DrapHeadStateEnum.HEAD_PULL_REFRESH_STATE);
			} else if (offset < 0) {
				_switchHeadState(DrapHeadStateEnum.HEAD_NORMAL_STATE);
			} else {

			}
		}
	}

	/***
	 * 手势抬起操作
	 * 
	 * @param event
	 */
	private void _doActionUp(MotionEvent event) {
		if (mHeadDelegate == null) {
			return;
		}
		mIsRecord = false;// 此时的touch事件完毕，要关闭。
		isScroller = true;// ListView可以Scrooler滑动.
		// mBack = false;
		// 如果下拉状态处于loading状态.
		if (mHeadState == DrapHeadStateEnum.HEAD_LOADING_STATE) {
			return;
		} else if (mHeadState == DrapHeadStateEnum.HEAD_NORMAL_STATE) {

		} else if (mHeadState == DrapHeadStateEnum.HEAD_PULL_REFRESH_STATE) {
			mHeadDelegate.getView().setPadding(0, -1 * mHeadViewHeight, 0, 0);
			_switchHeadState(DrapHeadStateEnum.HEAD_NORMAL_STATE);
		} else if (mHeadState == DrapHeadStateEnum.HEAD_RELEASE_REFRESH_STATE) {
			mHeadDelegate.getView().setPadding(0, 0, 0, 0);
			_switchHeadState(DrapHeadStateEnum.HEAD_LOADING_STATE);
			if (refreshDelegate != null) {
				refreshDelegate.onHeadRefresh();
			}
		}
	}

	// ----------------------- OnScrollListener -----------------------
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		mFirstItemIndex = firstVisibleItem;
	}
}
